<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;


class Common extends Controller
{
    public function _initialize()
    {
        $request = Request::instance();

        $path = strtolower($request->module().'/'.$request->controller().'/'.$request->action());


        // if(!$this->checkAuth($path)){
        //     if(session('uid')){
        //         $this->error('没有权限');
        //     }else{
        //         $this->error('你还没有登录，请先登录');
        //     }
            
        // }

        $auths = config('auth');

        // var_dump($path);

        // var_dump($auths );

        if(in_array($path,$auths)){
            if(!session('uid')){
                $this->error('你还没有登录，请先登录');
            }
        }
    }

    public function checkAuth($path)
    {
        $rule = Db::table('fly_auth_rule')->where('rule',$path)->find();

        if(!$rule){
            return true;
        }

        if(!session('uid')){
            return false;
        }


        $roles= Db::table('fly_auth_user_role')
        ->alias('t1')
        ->join('fly_auth_role t2','t1.role_id=t2.role_id')
        ->where('t1.uid',session('uid'))
        ->select();
        

        $rules = [];


        foreach ($roles as $role) {
           $rules = array_merge($rules,explode(',',$role['rules']));
        }

        $rules = array_unique($rules);

        $rules = Db::table('fly_auth_rule')->where('rule_id','in',$rules)->column('rule');

       if(in_array($path,$rules)){
            return true;
       }else{
            return false;
       }
        
    }
    
}